import Toast from "tdesign-miniprogram/toast/index";
import ActionSheet, {
  ActionSheetTheme,
} from "tdesign-miniprogram/action-sheet";
import { splitAddress, addressParse } from "../../../utils/address";
import { getMergeData } from "../../../utils/index";
import { areaData, modeItems } from "../../../config/index";
import {
  saveFishingSpot,
  getFishingSpotById,
} from "../../../api/fishing-spots";

Page({
  data: {
    spotId: "",
    modeItems,
    areaData,
    modeName: "",
    computedAddress: "",
    formData: {
      name: "",
      description: "",
      mode: "",
      contactName: "",
      contactPhone: "",
      contactWechat: "",
      provinceCode: "",
      province: "",
      cityCode: "",
      city: "",
      districtCode: "",
      district: "",
      address: "",
      latitude: null,
      longitude: null,
    },
    areaPickerVisible: false,
    dialogVisible: false,
    fileList: [],
  },

  setAddress(data = {}, extra) {
    let { province, city, district, provinceCode } = data;

    if (!provinceCode) {
      const parseInfo = addressParse(province, city, district);
      // console.log("==addressParse===", parseInfo);
      data.provinceCode = parseInfo.provinceCode;
      data.cityCode = parseInfo.cityCode;
      data.districtCode = parseInfo.districtCode;
    }

    const finalData = {};
    Object.keys(data).map((key) => {
      finalData[`formData.${key}`] = data[key];
    });
    if (extra) {
      Object.keys(extra).map((key) => {
        finalData[`${key}`] = extra[key];
      });
    }
    console.log("address info", finalData);
    let computedAddress = "";
    if (province) {
      computedAddress = `${province || "/"}${city || "/"}${district}`;
    }
    finalData.computedAddress = computedAddress;
    this.setData(finalData);
  },

  async onLoad(options) {
    const spotId = options.id || "";
    console.log("===setting page onLoad===", options, spotId);
    this.loadSpotInfo(spotId);
    this.setData({
      spotId,
    });
  },

  async loadSpotInfo(spotId) {
    let oldData;
    if (spotId) {
      oldData = await getFishingSpotById(spotId);
      console.log("------oldData----------", oldData);
    }
    if (!oldData) {
      this.reset();
      return;
    }
    console.log("=========formData===========", this.data.formData);

    const newData = getMergeData(this.data.formData, oldData);
    let fileList = [];

    console.log("------images----------", oldData.images);
    if (oldData.images) {
      fileList = oldData.images.split(",").map((url) => ({
        url,
        value: url,
      }));
    }

    this.setData({
      fileList,
      formData: {
        ...newData,
      },
    });
    this.onModeChange(newData.mode);
  },

  reset() {
    // this.setData({
    //   documentId: '',
    //   modeName: '',
    //   formData: {
    //     name: "",
    //   },
    //   areaPickerVisible: false,
    //   fileList: [],
    // });
    this.onActionSelected({
      detail: {
        selected: modeItems[0],
      },
    });
  },

  // 输入框
  onInputValue(e) {
    const { feild } = e.currentTarget.dataset;
    // console.log("---feild------", feild);
    if (feild === "address_select") {
      const { selectedOptions = [] } = e.detail;
      this.setAddress(
        {
          provinceCode: selectedOptions[0].value,
          province: selectedOptions[0].label,
          city: selectedOptions[1].label,
          cityCode: selectedOptions[1].value,
          districtCode: selectedOptions[2].value,
          district: selectedOptions[2].label,
        },
        {
          areaPickerVisible: false,
        }
      );
      return;
    } else if (feild === "address") {
      this.setData({
        "formData.address": e.detail.value,
      });
      return;
    }

    this.setData({
      [`formData.${feild}`]: e.detail.value,
    });
  },

  onActionOpen() {
    // 经营模式选择
    ActionSheet.show({
      theme: ActionSheetTheme.List,
      selector: "#t-action-sheet",
      context: this,
      items: modeItems,
    });
  },

  onActionSelected(e) {
    const { label, value } = e.detail.selected;
    this.setData({
      "formData.mode": value,
      modeName: label,
    });
  },

  onModeChange(mode) {
    const currentMode = modeItems.find((item) => item.value === mode);
    this.setData({
      "formData.mode": mode,
      modeName: currentMode?.label,
    });
  },

  onIconTap() {
    // 跳转到微信号获取介绍页面
    wx.navigateTo({
      url: "/pages/fishingspot/wechat-guide/wechat-guide",
    });
  },

  onPickArea() {
    this.setData({ areaPickerVisible: true });
  },

  builtInSearch({ code, name }) {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success: (res) => {
          if (res.authSetting[code] === false) {
            wx.showModal({
              title: `获取${name}失败`,
              content: `获取${name}失败，请在【右上角】-小程序【设置】项中，将【${name}】开启。`,
              confirmText: "去设置",
              confirmColor: "#FA550F",
              cancelColor: "取消",
              success(res) {
                if (res.confirm) {
                  wx.openSetting({
                    success(settinRes) {
                      if (settinRes.authSetting[code] === true) {
                        resolve();
                      } else {
                        console.warn("用户未打开权限", name, code);
                        reject();
                      }
                    },
                  });
                } else {
                  reject();
                }
              },
              fail() {
                reject();
              },
            });
          } else {
            resolve();
          }
        },
        fail() {
          reject();
        },
      });
    });
  },

  onSearchAddress() {
    console.log("onSearchAddress=======");
    this.builtInSearch({ code: "scope.userLocation", name: "地址位置" }).then(
      () => {
        wx.chooseLocation({
          success: (res) => {
            console.log("------chooseLocation-", res);
            if (res.name) {
              const { address, latitude, longitude } = res;
              console.log("---res---", splitAddress(res.address));
              const { province, city, district, detail } =
                splitAddress(address);

              console.log("---res---", province, city, district);

              this.setAddress({
                province, // 省份名称
                city, // 城市名称
                district, // 区域名称
                address: detail, // 详细地址
                latitude: latitude, // 纬度
                longitude: longitude, // 经度
              });
              return;
            }
            Toast({
              context: this,
              selector: "#t-toast",
              message: "地点为空，请重新选择",
              icon: "",
              duration: 1000,
            });
          },
          fail: function (res) {
            console.warn(`wx.chooseLocation fail: ${JSON.stringify(res)}`);
            if (res.errMsg !== "chooseLocation:fail cancel") {
              Toast({
                context: this,
                selector: "#t-toast",
                message: "地点错误，请重新选择",
                icon: "",
                duration: 1000,
              });
            }
          },
        });
      }
    );
  },

  // 图片上传成功
  onImageUploadChange(e) {
    const fileList = e.detail;
    console.log("onImageUploadChange=========", fileList);
    this.setData({
      fileList,
    });
  },

  async onSubmit() {
    const data = this.validateForm();
    console.log("=====validateForm=======", data);
    if (!data) {
      return;
    }

    wx.showLoading({
      title: "提交中...",
    });

    console.log("----data----", data);

    try {
      const result = await saveFishingSpot(this.data.spotId, data);
      if (result.error) {
        throw result.error;
      }
      wx.hideLoading();
      this.setData({
        dialogVisible: true,
      });
    } catch (error) {
      wx.hideLoading();
      console.error("保存钓场信息失败:", error);
      wx.showToast({
        title: "保存失败: " + (error.message || "网络错误"),
        icon: "none",
        duration: 3000,
      });
    }
  },
  validateForm() {
    const { formData, fileList } = this.data;
    const { contactPhone } = formData;

    const array = [
      { key: "name", title: "请输入钓场名字" },
      { key: "mode", title: "请选择经营模式" },
      { key: "contactName", title: "请输入联系人" },
      { key: "contactPhone", title: "请输入手机号" },
      { key: "contactWechat", title: "请输入微信号" },
      { key: "description", title: "请输入钓场描述" },
      { key: "provinceCode", title: "请选择钓场省市区" },
      { key: "address", title: "请输入钓场位置" },
    ];
    for (let index = 0; index < array.length; index++) {
      const item = array[index];
      const { key, value } = item;
      if (!formData[key] || formData[key].trim() === "") {
        wx.showToast({
          title: item.title,
          icon: "none",
        });
        return false;
      }
    }
    if (!/^1[3-9]\d{9}$/.test(contactPhone)) {
      wx.showToast({
        title: "请输入正确的手机号",
        icon: "none",
      });
      return false;
    }
    console.log("=====fileList=====", fileList);
    const images = (fileList || []).map((el) => el.value).join(",");
    if (images.length <= 0) {
      wx.showToast({
        title: "请上传钓场图片",
        icon: "none",
      });
      return false;
    }
    return {
      ...formData,
      images,
    };
  },
  closeDialog() {
    this.setData({ dialogVisible: false });
    wx.navigateBack();
  },
});
